from flask import current_app
from flask import g, jsonify
from flask import request
from flask import session

from info import constants
from info import db
from info.models import User, Category, News
from info.utitls.common import user_login_data
from info.utitls.pic_storage import pic_storage
from info.utitls.response_code import RET
from . import profile_bp
from flask import render_template

@profile_bp.route("/news_list")
@user_login_data
def news_list():
        user = g.user
        # 第一次的时候没有携带P页码， 用默认值
        p = request.args.get("p", 1)
        try:
            p = int(p)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news_list = []
        current_page = 1
        total_page = 1
        if user:
            try:
                paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)

                # 当前页码所有数据
                news_list = paginate.items
                current_page = paginate.page
                total_page = paginate.pages
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
        news_dict_list = []
        for news in news_list if news_list else []:
            news_dict_list.append(news.to_review_dict())

        data = {
            "news_list": news_dict_list,
            "current_page": current_page,
            "total_page": total_page

        }
        return render_template("profile/user_news_list.html", data=data)







@profile_bp.route("/news_release", methods=["POST", "GET"])
@user_login_data
def news_release():
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询分类数据异常")
        category_dict_list = []
        for category in categories if categories else []:
            category_dict_list.append(category)
        category_dict_list.pop(0)
        data = {
            "categories": category_dict_list
        }
        return render_template("profile/user_news_release.html", data=data)
    """
    获取参数
    title： 标题  cid：分类id   digest：摘要
    index_image： 新闻主图片  content： 内容  source： 来源（默认个人发布）

    """
    # 应为前段使用的是ajaxSubmit所有数据是form表单提交的
    params_dict = request.form
    title = params_dict.get("title")
    cid = params_dict.get("category_id")
    digest = params_dict.get("digest")
    # 注意： 图片从files中提取数据
    index_image = request.files.get("index_image")
    content = params_dict.get("content")
    user = g.user
    source = "个人发布"
    if not all([title, cid, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    image_data = index_image.read()
    try:
        image_name = pic_storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片异常")
    # 创建新闻对象
    news = News()
    news.title = title
    news.category_id = cid
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.content = content
    news.source = source
    news.user_id = user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据异常")
    return jsonify(errno=RET.OK, errmsg="发布新闻成功")





@profile_bp.route("/news_collect")
@user_login_data
def news_collect():
    user = g.user
    # 第一次的时候没有携带P页码， 用默认值
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    collection_news_list = []
    current_page = 1
    total_page = 1
    if user:
        try:
            paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
            # 当前页码所有数据
            collection_news_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
    news_dict_list = []
    for news in collection_news_list if collection_news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "collections": news_dict_list,
        "current_page": current_page,
        "total_page": total_page

    }
    return render_template("profile/user_collection.html", data=data)



@profile_bp.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    # 展示/修改密码
    user = g.user
    if request.method == "GET":
        return render_template("profile/user_pass_info.html")
    param_dict = request.json
    old_password = param_dict.get("old_password")
    new_password = param_dict.get("new_password")
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="旧密码填写错误")
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
    return jsonify(errno=RET.OK, errmsg="OK")



@profile_bp.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_info():
    # 返回用户头像
    user = g.user
    if request.method == "GET":
        return render_template("profile/user_pic_info.html")
    # 修改用户头像
    """
    获取参数
        1.1. pic： 图片数据  user： 当前用户

    校验参数
        非空判断
    逻辑处理
        调用七牛云工具将图片数据上传， 返回一个图片名称
        将图片名称保存到用户对象avatar_url身上
        返回完整的图片url
    返回值
    """
    print("开始")
    pic_data = request.files.get("avatar").read()
    if not pic_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    try:
        pic_name = pic_storage(pic_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云异常")
    user.avatar_url = pic_name
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存图片数据异常")
    full_url = constants.QINIU_DOMIN_PREFIX + pic_name
    # 返回完整的url
    data = {

        "avatar_url": full_url
    }
    print("保存图片成功")
    return jsonify(errno=RET.OK, errmsg="保存图片成功", data=data)




@profile_bp.route("/base_info", methods=["POST", "GET"])
@user_login_data
def base_info():
    # 展示/修改用户基本资料
    user = g.user
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("profile/user_base_info.html", data=data)
    param_dict = request.json
    signature = param_dict.get("signature")
    nick_name = param_dict.get("nick_name")
    gender = param_dict.get("gender")
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_list = User.query.filter(User.nick_name == nick_name).all()
    if user_list:
        return jsonify(errno=RET.DATAERR, errmsg="用户昵称已经存在")
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    session["nick_name"] = nick_name
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户对象异常")
    return jsonify(errno=RET.OK, errmsg="ok")




@profile_bp.route("/info")
@user_login_data
def user_info():
    # 用户个人中心
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("profile/user.html", data=data)